package com.gitee.loyo.jdbc

import com.gitee.loyo.KSQL
import java.sql.Connection
import javax.sql.DataSource

open class Ds(private val ds: DataSource) : DataSource by ds {

    fun <T> open(transaction: Int = Connection.TRANSACTION_NONE, fn: (Conn) -> T): T{
        val conn = Conn.create(this.connection)
        JDBCListener.onOpenedListener?.invoke(this, conn)
        conn.use { conn ->
            val originTransaction = conn.transactionIsolation
            val autoCommit = conn.autoCommit
            if(transaction > Connection.TRANSACTION_NONE){
                if(originTransaction != transaction) {
                    conn.transactionIsolation = transaction
                }
                conn.autoCommit = false
            }
            try{
                return fn(conn)
            }finally {
                if(conn.transactionIsolation != originTransaction)
                    conn.transactionIsolation = originTransaction
                if(conn.autoCommit != autoCommit)
                    conn.autoCommit = autoCommit
            }
        }
    }

    override fun getConnection(): Connection {
        val connection = ds.connection
        KSQL.log("open connection")
        return Conn.create(connection)
    }

}